//////////////////////////////////////////////////////////////////////////
///	\file:	SocketWriter.h
///	Copyright (MingYou) 2009 - All Rights Reserved
///	Author:	Robert.Ma
///	Date:	[2009/05/14]
///	Description:
///		
//////////////////////////////////////////////////////////////////////////
#pragma once

#include "MThread.h"
#include <list>

class CSocketWriter : public CMThread
{
public:
	struct DataPacket
	{
		//	buffer length
		int iLen;
		//	actual buffer
		BYTE* pBuf;
	};

	CSocketWriter(void);
	virtual ~CSocketWriter(void);

	BOOL Initialize(SOCKET* pSocket, DWORD dwParentID);
	void Release();

	int Write(const BYTE* pData, DWORD dwLen);

protected:
	virtual DWORD Execute();

	virtual void PreCreate();
	virtual void AfterCreate();
	virtual void PreClose();
	virtual void AfterClose();

private:
	void ClearBuffer();
	void SocketSendBuffer();
	BOOL EnterBuffer();
	void LeaveBuffer();

	int SocketWrite(BYTE* pData, DWORD dwLen);

	void FreePacket(DataPacket* pPack);

	std::list<DataPacket*>	m_SendBuffer;

	HANDLE	m_hMutex;

	SOCKET*	m_pSocket;
	int		m_nSocketError;
	DWORD	m_dwParentID;
};
